package com.ycsj.goldmedalnewconcept.common.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.ycsj.common.adapter.ShowPicGvAdapter;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.manager.PickChooseManager;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.MaxTextLengthFilter;
import com.ycsj.common.utils.SnackbarUtil;
import com.ycsj.common.utils.StateBarUtil;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.common.view.scroll.MyGridView;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.bean.ResultInfo;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.LpUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPicker;
import me.shaohui.advancedluban.Luban;
import me.shaohui.advancedluban.OnMultiCompressListener;
import okhttp3.Call;

/**
 * 发布公告
 */
public class SendNoticeActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    @BindView(R.id.main)
    LinearLayout llMain;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.lv_edit)
    ImageView lvEdit;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.et_tag)
    EditText etTag;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.tv_new_num)
    TextView tvNewNum;
    @BindView(R.id.mgv)
    MyGridView mgv;

    //适配对象
    private ShowPicGvAdapter adapter;

    //填充适配器的图片地址
    private List<String> mPicPaths;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_send_notice;
    }

    @Override
    protected void init() {
        //沉浸状态栏
        StateBarUtil.customImmerseBar(this);

        //初始化标题栏
        initTitle();

        //限定输入框的内容长度
        initListener();

        //初始化选择相册
        initGvShowPic();
    }


    /**
     * 初始化标题栏
     */
    private void initTitle() {
        tvTitle.setText("发布公告");
        lvEdit.setVisibility(View.VISIBLE);
        //动态适发布按钮的宽高
        RelativeLayout.LayoutParams lp = LpUtils.getRelatLp(UiUtils.dp2px(78), UiUtils.dp2px(32));
        lp.addRule(RelativeLayout.CENTER_VERTICAL);
        lp.leftMargin = 16;
        lvEdit.setLayoutParams(lp);
        lvEdit.setImageResource(R.drawable.comment_send);

    }


    /**
     * 设置输入框的长度监听
     */
    private void initListener() {
        etTag.setFilters(new InputFilter[]{new MaxTextLengthFilter(21)});
        etContent.setFilters(new InputFilter[]{new MaxTextLengthFilter(501)});

        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String inputText = etContent.getText().toString().trim();
                if (TextUtils.isEmpty(inputText)) {
                    tvNewNum.setText("0/500");
                } else {
                    if (inputText.length() > 201) {
                        tvNewNum.setText("500/500");
                    } else {
                        tvNewNum.setText(inputText.length() + "/500");
                    }
                }
            }
        });
    }

    /**
     * 初始化选择相册的九宫格展示
     */
    private void initGvShowPic() {
        mPicPaths = new ArrayList<>();
        adapter = new ShowPicGvAdapter(this, mPicPaths);
        mgv.setAdapter(adapter);
        mgv.setOnItemClickListener(this);
    }


    /**
     * 页面控件点击事件
     *
     * @param v
     */
    @OnClick({R.id.iv_back, R.id.lv_edit})
    public void clickEvent(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                //返回
                finish();
                break;

            case R.id.lv_edit:
                //发布按钮
                doCommitAction();
                break;
        }
    }


    /**
     * 发布
     */
    private void doCommitAction() {

        // 主题
        final String tag = etTag.getText().toString().trim();
        if (TextUtils.isEmpty(tag)) {
            SnackbarUtil.ShortSnackbar(llMain, "请输入活动主题", 0).show();
            return;
        }

        // 内容
        final String content = etContent.getText().toString().trim();
        if (TextUtils.isEmpty(content) && (mPicPaths == null || mPicPaths.size() == 0)) {
            SnackbarUtil.ShortSnackbar(llMain, "请完善公告信息。", 0).show();
            return;
        }


        //图片
        if (mPicPaths == null || mPicPaths.size() == 0) {
            //直接上传
            CustomDialogManager.show(this, "上传中");
            httpUploadText(tag, content);
        } else {
            //遍历选择的图片进行压缩后进行上传
            //做压缩处理
            CustomDialogManager.show(this, "上传中");
            List<File> files = new ArrayList<>();
            for (int i = 0; i < mPicPaths.size(); i++) {
                File file = new File(mPicPaths.get(i));
                files.add(file);
            }

            //使用Luban做压缩图片处理
            Luban.compress(this, files).setMaxSize(150).setMaxHeight(1280).setMaxWidth(720).putGear(Luban.CUSTOM_GEAR).launch(new OnMultiCompressListener() {

                @Override
                public void onStart() {
                    //压缩开始
                }

                @Override
                public void onSuccess(List<File> fileList) {
                    //压缩成功后的回调,上传该集合的文件
                    httpUpload(fileList, tag, content);
                }

                @Override
                public void onError(Throwable e) {
                    //压缩错误
                }
            });
        }
    }

    /**
     * 发布无图片的公告
     *
     * @param tag     主题
     * @param content 内容
     */
    private void httpUploadText(String tag, String content) {

        Map<String, String> map = new HashMap<>();
        map.put("type", "4");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", "3");
        map.put("tag", tag);
        map.put("content", content);
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("platform", "2");

        HttpUtils.post(HttpAddress.APPLYNOTICE, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast("服务器异常,上传失败", false);
                CustomDialogManager.dissmiss();
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();

                ResultInfo info = null;
                try {
                    info = GsonUtil.jsonToBean(response, ResultInfo.class);
                } catch (Exception e) {
                    Log.i("test", "数据解析异常");
                }

                if ("200".equals(info.getState())) {
                    ToastUtils.showShort("发布成功");
                    ////通知公告页面进行刷新
                    BusInfo busInfo = new BusInfo();
                    busInfo.type = NoticeActivity.UPDATE;
                    EventBus.getDefault().post(busInfo);
                    finish();
                } else if ("101".equals(info.getState())) {
                    ToastUtils.showShort("发布失败，参数错误");
                } else {
                    ToastUtils.showShort("发布失败，错误代码" + info.getState());
                }
            }
        });
    }

    /**
     * 发布公告消息的网络请求
     *
     * @param fileList 上传的文件
     * @param tag      主题
     * @param content  内容
     */
    private void httpUpload(List<File> fileList, String tag, String content) {

        Map<String, String> map = new HashMap<>();
        map.put("type", "3");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", "3");
        map.put("tag", tag);
        map.put("content", content);
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("platform", "2");

        Map<String, File> fileMap = new HashMap<>();
        for (int i = 0; i < fileList.size(); i++) {
            fileMap.put(System.currentTimeMillis() + i + i + ".jpg", fileList.get(i));
        }
        OkHttpUtils.post().url(HttpAddress.APPLYNOTICE).params(map).files("picture", fileMap).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast("服务器异常,上传失败", false);
                CustomDialogManager.dissmiss();
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                ResultInfo info = null;
                try {
                    info = GsonUtil.jsonToBean(response, ResultInfo.class);
                } catch (Exception e) {
                    Log.i("test", "数据解析异常");
                }

                if ("200".equals(info.getState())) {
                    ToastUtils.showShort("发布成功");
                    ////通知公告页面进行刷新
                    BusInfo busInfo = new BusInfo();
                    busInfo.type = NoticeActivity.UPDATE;
                    EventBus.getDefault().post(busInfo);
                    finish();
                } else if ("101".equals(info.getState())) {
                    ToastUtils.showShort("发布失败，参数错误");
                } else {
                    ToastUtils.showShort("发布失败，错误代码" + info.getState());
                }
            }
        });
    }


    /**
     * 选择图片的条目点击事件
     *
     * @param view
     * @param position
     * @param l
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
        Object itemAdapter = parent.getAdapter();
        if (itemAdapter instanceof ShowPicGvAdapter) {
            if (mPicPaths.size() != 9) {
                if (position == ((ShowPicGvAdapter) itemAdapter).getCount() - 1) {
                    PickChooseManager.startPhotoPickActivity(SendNoticeActivity.this, 9 - mPicPaths.size());
                } else {
                    PickChooseManager.startShowBigActivity(SendNoticeActivity.this, mPicPaths, position);
                }
            } else {
                PickChooseManager.startShowBigActivity(SendNoticeActivity.this, mPicPaths, position);
            }
        }
    }

    /**
     * 请求图库后的回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                ArrayList<String> photos =
                        data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);

                for (int i = 0; i < photos.size(); i++) {
                    mPicPaths.add(photos.get(i));
                }
                //通知适配器刷新
                adapter.notifyDataSetChanged();
            }
        }
    }
}
